import React from 'react';
import { withRouter, connect } from 'umi';
import { Form, Input, Spin } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { TitleControl } from '@/pages/Recruitment/components';
import { getEmployeeInfo } from '@/pages/OnboardAndLeave/TransferPost/services';

import {
    children as formItems,
    excludeItems
} from '@/pages/WorkFlow/components/FormControls/formConfig/custom/transferPositionApply';
import { getSummary } from '@/pages/WorkFlow/Flow/utils';
import { renderPartTimeDuty } from '@/utils/utils';

import { Info, Profile, Content } from './containers';

const titleProps = {
    styleTitle: title => <div style={{ fontWeight: 'bold', fontSize: 16, paddingLeft: 8 }}>{title}</div>,
    showButton: false,
    bottomBorder: false
};

const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 }
};

// 调岗申请
const requiredItems = formItems.filter(item => !excludeItems.includes(item.key));
const TransferPositionApply = ({ form, formValueMap = {}, location, dataSource, user = {} }) => {
    const { query = {} } = location;
    const { getFieldDecorator, setFieldsValue, getFieldValue } = form;
    const { children = [] } = dataSource;

    const employeeCode = getFieldValue('applyEmployeeCode') ?? formValueMap.applyEmployeeCode ?? query.employeeCode;

    const isSelf = user.employeeCode === employeeCode;

    const { data = {}, run, loading } = useRequest(code => getEmployeeInfo({ employeeCode: code }), {
        manual: true,
        ...defaultFormatResult
    });

    const checkEditable = fieldName =>
        children.some(item => item.formId === fieldName && item.options && !item.options.disabled);

    const commonProps = {
        employeeCode,
        form,
        checkEditable,
        isSelf,
        formValueMap: employeeCode
            ? {
                  ...data,
                  applyEmployeeCode: employeeCode,
                  applyEmployeeName: data.employeeName,
                  currentCompanyCode: data.administrativeOrganizationCode,
                  currentCompanyName: data.administrativeOrganizationName,
                  currentOrganizationCode: data.organizationCode,
                  currentOrganizationName: data.organizationName,
                  currentDutyName: data.dutyAlias,
                  currentDutyCode: data.dutyCode,
                  transferPositionType: 1,
                  leaderEmployeeName: data.leaderName,
                  fullOrganizationName: data.organizationVOList?.[0]?.fullOrganizationName,
                  partTimeDuty: renderPartTimeDuty(data.partTimeDutyAliasList),
                  transferRankValue: data.rankValue,
                  transferToCompanyCode: data.administrativeOrganizationCode,
                  transferToCompanyName: data.administrativeOrganizationName,
                  ...formValueMap
              }
            : {}
    };

    React.useEffect(() => {
        if (!employeeCode) return;
        run(employeeCode);
    }, [employeeCode]);

    React.useEffect(() => {
        const nextValue = commonProps.formValueMap;
        const updater = {};
        formItems.forEach(item => {
            updater[item.key] = nextValue[item.key];
        });
        setFieldsValue(updater);
    }, [JSON.stringify(commonProps.formValueMap)]);

    const formatOrg = orgName => {
        const nameArr = orgName?.split('/') || [];
        return nameArr[nameArr.length - 1];
    };
    React.useEffect(() => {
        const nextValue = form.getFieldsValue();
        const summary = getSummary({
            调岗对象: nextValue.applyEmployeeName,
            原组织机构: nextValue.currentOrganizationName,
            原岗位: nextValue.currentDutyName,
            新组织机构: formatOrg(nextValue.transferToOrganizationName),
            新岗位: nextValue.transferToDutyName
        });
        setFieldsValue({ applicationAbstract: summary });
    }, [JSON.stringify(form.getFieldsValue())]); // 性能？

    return (
        <Form {...formItemLayout}>
            <Spin spinning={loading}>
                <TitleControl title="个人信息" {...titleProps}>
                    <Profile {...commonProps} />
                </TitleControl>
                <TitleControl title="调岗信息" {...titleProps}>
                    <Info {...commonProps} />
                </TitleControl>
                <TitleControl title="调岗内容" {...titleProps}>
                    <Content {...commonProps} />
                </TitleControl>
                <div style={{ display: 'none' }}>
                    {requiredItems.map(item => (
                        <Form.Item key={item.key}>{getFieldDecorator(item.key)(<Input />)}</Form.Item>
                    ))}
                    <Form.Item>{form.getFieldDecorator('applicationAbstract')(<Input />)}</Form.Item>
                </div>
            </Spin>
        </Form>
    );
};

export default withRouter(
    connect(({ user }) => ({
        user: user.currentUser
    }))(TransferPositionApply)
);
